package cn.yunbamboos.rest.service.logs;

import cn.hutool.core.util.ObjUtil;
import cn.yunbamboos.rest.service.logs.event.LogEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;

import java.time.LocalDateTime;

public class LogMetadataThreadLocal {

    private static final Logger logger = LoggerFactory.getLogger(LogMetadataThreadLocal.class);

    private final static ThreadLocal<LogMetadata> local = new ThreadLocal<>();

    public static LogMetadata get() {
        LogMetadata operateLog = local.get();
        if (ObjUtil.isNull(operateLog)) {
            operateLog = new LogMetadata();
            local.set(operateLog);
        }
        return operateLog;
    }

    public static void send(ApplicationEventPublisher applicationEventPublisher, Object source){
        try {
            LogMetadata operateLog = local.get();
            if (ObjUtil.isNotNull(operateLog)) {
                LogEvent event = new LogEvent(source);
                event.setDelegate(operateLog);
                applicationEventPublisher.publishEvent(event);
            }
        } catch (Exception e){
            logger.error("send log event error", e);
        }finally {
            local.remove();
        }
    }

    public static void setTraceId(String traceId) {
        get().setTraceId(traceId);
    }

    public static void setLoginTraceId(String loginTraceId) {
        get().setLoginTraceId(loginTraceId);
    }

    public static void setUserId(long userId) {
        get().setUserId(userId);
    }

    public static void setClientIp(String clientIp) {
        get().setClientIp(clientIp);
    }

    public static void setBrowser(String browser) {
        get().setBrowser(browser);
    }

    public static void setServiceName(String serviceName) {
        get().setServiceName(serviceName);
    }

    public static void setServicePath(String servicePath) {
        get().setServicePath(servicePath);
    }

    public static void setRealUrl(String realUrl) {
        get().setRealUrl(realUrl);
    }

    public static void setStartTime(LocalDateTime startTime) {
        get().setStartTime(startTime);
    }

    public static void setTime(long time) {
        get().setTime(time);
    }

    public static void setCode(int code) {
        get().setCode(code);
    }

    public static void setMsg(String msg) {
        get().setMsg(msg);
    }

    public static void setIn(String in) {
        get().setIn(in);
    }

    public static void setOut(String out) {
        get().setOut(out);
    }

    public static void setAttribute(String key, Object value) {
        get().setAttribute(key, value);
    }

}
